const jwt = require('jsonwebtoken');
const config = require('./config');

/**
 * 生成JWT令牌
 * @param {Object} user 用户对象
 * @returns {String} JWT令牌
 */
const generateToken = (user) => {
  const payload = {
    id: user.id,
    email: user.email,
    role: 'user'
  };
  return jwt.sign(
    payload,
    config.jwt.secret,
    {
      expiresIn: config.jwt.expiresIn,
      issuer: config.jwt.issuer
    }
  );
};

// 生成管理员JWT Token
const generateAdminToken = (admin) => {
  const payload = {
    id: admin.id,
    username: admin.username,
    role: 'admin',
    permissions: admin.permissions || []
  };

  return jwt.sign(payload, config.jwt.secret, {
    expiresIn: config.jwt.expiresIn,
    issuer: config.jwt.issuer
  });
};

/**
 * 验证JWT令牌
 * @param {String} token JWT令牌
 * @returns {Object} 验证结果
 */
const verifyToken = (token) => {
  try {
    const decoded = jwt.verify(token, config.jwt.secret);
    return {
      valid: true,
      decoded
    };
  } catch (error) {
    console.error(`JWT令牌验证失败:`, error.message);
    return {
      valid: false,
      message: error.message
    };
  }
};

module.exports = {
  generateToken,
  generateAdminToken,
  verifyToken
}; 